package com.orhon.smartcampus.modules.systemctl.fetcher;


import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.orhon.smartcampus.basicComponents.Result;
import com.orhon.smartcampus.modules.systemctl.dao.OperationUserRelationDao;
import com.orhon.smartcampus.modules.systemctl.entity.OperationUserRelation;
import com.orhon.smartcampus.modules.systemctl.entity.Operations;
import com.orhon.smartcampus.modules.systemctl.gqlModel.GQLOperation;
import com.orhon.smartcampus.modules.systemctl.gqlModel.GQLSchoolOperationUsers;
import com.orhon.smartcampus.modules.systemctl.mm.OperationMapper;
import com.orhon.smartcampus.modules.systemctl.mm.OperationUserMapper;
import com.orhon.smartcampus.modules.user.entity.Users;
import com.orhon.smartcampus.modules.user.gqlModel.GQLUser;
import com.orhon.smartcampus.modules.user.mm.UserMapper;
import com.orhon.smartcampus.utils.ObjectToMap;
import com.orhon.smartcampus.utils.Util;

import graphql.schema.DataFetcher;
import graphql.schema.DataFetchingEnvironment;

@Component
public class OperationUsersRecordFetcher implements DataFetcher {


	@Autowired
	OperationUserRelationDao operationUserRelationDao;

	@Override
	public Object get(DataFetchingEnvironment env) throws Exception {

		ArrayList<GQLSchoolOperationUsers> arrayList = new ArrayList<GQLSchoolOperationUsers>();
		String hql = "from OperationUserRelation where deleted_at = null ";
		if (env.containsArgument("condition")) {
			HashMap<String, Object> map = ObjectToMap.to(env.getArgument("condition"));
			if (map.get("id") != null) {
				hql += " and id  "+ Util.decide (map.get("id"));
			}
			if (map.get("user_id") != null) {
				hql += " and user_id " + Util.decide(map.get("user_id"));
			}
			if (map.get("operation_id") != null) {
				hql += " and operation_id " + Util.decide(map.get("operation_id"));
			}

		}
		List<OperationUserRelation> items = operationUserRelationDao.find(hql, null, 0, 0);
		for (OperationUserRelation item : items) {
			if(item!=null) {
				GQLUser sqlUser = null;
				if (env.getSelectionSet().contains("data/user")){
					Users users = item.getUserUsersByUserId();
					sqlUser = UserMapper.MAPPER.mapUser(users);
				}
				GQLOperation operations1 = null;
				if (env.getSelectionSet().contains("data/operation")){
					Operations operations = item.getSystemctlOperationsByOperationId();
					operations1 = OperationMapper.MAPPER.toOperations(operations);
				}
				GQLSchoolOperationUsers empty = OperationUserMapper.MAPPER.toEmpty(item);
				empty.setUser(sqlUser);
				empty.setOperation(operations1);
				arrayList.add(empty);
			}
		}
		Long total = 0L;
		if (env.getSelectionSet().contains("total")) {
			total = operationUserRelationDao.getTotalCount(hql);
		}
		return Result.ok().put("data", arrayList).put("total", total);


	}



}
